import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/Layout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册', requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: '/host',
        name: 'Host',
        component: () => import('@/views/Host.vue'),
        meta: { title: '主机管理' }
      },
      {
        path: '/host-group',
        name: 'HostGroup',
        component: () => import('@/views/HostGroup.vue'),
        meta: { title: '主机组管理' }
      },
      {
        path: '/project',
        name: 'Project',
        component: () => import('@/views/Project.vue'),
        meta: { title: '项目管理' }
      },
      {
        path: '/environment',
        name: 'Environment',
        component: () => import('@/views/Environment.vue'),
        meta: { title: '环境管理' }
      },
      {
        path: '/user',
        name: 'User',
        component: () => import('@/views/User.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: '/user-group',
        name: 'UserGroup',
        component: () => import('@/views/UserGroup.vue'),
        meta: { title: '用户组管理' }
      },
      {
        path: '/terminal/:id',
        name: 'Terminal',
        component: () => import('@/views/Terminal.vue'),
        meta: { title: 'SSH终端' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn')
  
  // 如果路由需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isLoggedIn) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // 如果已登录，访问登录页时跳转到仪表盘
    if (isLoggedIn && (to.path === '/login' || to.path === '/register')) {
      next('/dashboard')
    } else {
      next()
    }
  }
})

export default router
